﻿using Authentication.Model.Interface;
using Authentication.Model.Model;
using Common.Contract;
using Common.Contract.Authentication;
using Common.Contract.Authentication.Identifier;
using Common.Contract.Authentication.Request;
using Common.Service.Command;
using Common.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Authentication.ServiceCommand
{
    public class UpdateRoleServiceCommand : ProviderServiceCommand<IRoleProvider, UpdateRoleRequest, ResponseRecord>
    {
        public UpdateRoleServiceCommand(IRoleProvider providers) : base(providers) { }
        protected override void Validate(UpdateRoleRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (request.Record == null)
            {
                throw new ArgumentException("Record must be set", "request");
            }
            if (!RoleIdentifier.IsValid(request.Record.RoleIdentifier))
            {
                throw new ArgumentException("RoleIdentifier is invalidate", "request");
            }
        }

        protected override bool OnExecute(ResponseRecord response)
        {
            var applicationKey = Request.Header.ApplicationKey;
            var role = new ApplicationRule
            {
                Active = Request.Record.Active.HasValue ? Request.Record.Active.Value.ToBooleanString() : null,
                ApplicationKey = applicationKey.ToString().ToUpper(),
                Description = Request.Record.Description,
                RuleId = new RoleIdentifier(Request.Record.RoleIdentifier).PersistableID,
                RuleNameEnglish = Request.Record.Name,
                RuleNameLocal = Request.Record.Name
            };

            var roleId = Providers.Update(role);
            return roleId;
        }
    }
}
